import { Component, OnInit } from '@angular/core';
import { NzModalRef, NzMessageService } from 'ng-zorro-antd';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ProjectService } from 'src/app/core/service/project.service';

@Component({
  selector: 'app-add-project',
  templateUrl: './add-project.component.html',
  styleUrls: ['./add-project.component.scss']
})
export class AddProjectComponent implements OnInit {
  projectForm: FormGroup;
  info: any;

  constructor(
    private modal: NzModalRef,
    private message: NzMessageService,
    private projectService: ProjectService,
    fb: FormBuilder
  ) {
    this.projectForm = fb.group({
      projectName: ['', Validators.compose([Validators.required])],
      version: ['', Validators.compose([Validators.required])],
      description: [''], // 非必填项，默认值为什么？
    });
  }

  /**
   * 创建项目
   */
  addproject() {
    console.log('提交', this.projectForm.controls);
    // tslint:disable-next-line:forin
    for (const c in this.projectForm.controls) {
      this.projectForm.controls[c].markAsTouched();
    }

    if (this.projectForm.valid) {
      this.info = {
        projectName: this.projectForm.controls.projectName.value,
        version: this.projectForm.controls.version.value,
        describe: this.projectForm.controls.description.value
      };
      this.addService(this.info);
    } else {
      this.message.error('表单校验失败', { nzDuration: 10000 });
    }
  }

  /**
   * 服务器请求
   */
  addService(info: any) {
    this.projectService.addProject(info)
      .subscribe((OrgUserData) => {
        console.log(OrgUserData);
        if (OrgUserData.status) {
          this.message.success('添加成功!', {
            nzDuration: 10000
          });
          this.modal.destroy();
        } else {
          this.message.error('添加失败!请检查后重新填写', {
            nzDuration: 10000
          });
        }
      });
  }

  destroyModal(): void {
    this.modal.destroy({ data: 'this the result data' });
  }

  ngOnInit() {
  }

}
